import NavBar from '../../components/NavBar'
import Input from '../../components/Input'
import styles from './index.module.scss'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { login, sendCode } from '../../store/action/login'
import { useState } from 'react'
import { useHistory } from 'react-router-dom'
import { useLocation } from 'react-router-dom'
// import { Toast } from 'antd-mobile'
export default function Login() {
  const history = useHistory()
  const dispatch = useDispatch()
  const [time, setTime] = useState(0)
  const location = useLocation()

  const onExtraClick = async () => {
    if (time > 0) return
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      formik.setTouched({
        mobile: true,
      })
      return
    }
    try {
      await dispatch(sendCode(mobile))
      // Toast.success('保存成功', 1)
      // 开启倒计时
      setTime(5)

      let timeId = setInterval(() => {
        // 当我们每次都想要获取最新的状态。需要写成 箭头函数的形式
        setTime((time) => {
          if (time === 1) {
            clearInterval(timeId)
          }
          return time - 1
        })
      }, 1000)
    } catch (err) {
      if (err.response) {
        // Toast.info(err.response.data.message, 1)
      } else {
        // Toast.info('服务器繁忙，请稍后重试', 1)
      }
    }
  }
  const formik = useFormik({
    initialValues: {
      mobile: '13911111111',
      code: '246810',
    },
    async onSubmit(values) {
      // 当表单提交的时候会触发
      // console.log(values)

      await dispatch(login(values))
      // Toast.success('登录成功')
      // 跳转到首页
      // history.push('/home')
      if (location.state.from) {
        history.push(location.state.from.pathname) //这里加了个state
      } else {
        history.push('/home')
      }
      // console.log(location)
    },
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('手机号不能为空')
        .matches(/^1[3-9]\d{9}$/, '手机号格式错误'),
      code: Yup.string()
        .required('验证码不能为空')
        .matches(/\d{6}$/, '验证码格式错误'),
    }),
  })
  const {
    values: { mobile, code },
    handleChange,
    handleSubmit,
    errors,
    handleBlur,
    touched,
    isValid,
  } = formik
  // console.log(formik)
  return (
    <div className={styles.root}>
      {/* 标题 */}
      <NavBar extra=" ">登录</NavBar>
      {/* 内容 */}
      <div className="content">
        <form onSubmit={handleSubmit}>
          <h3>短信登录</h3>
          <div className="input-item">
            {/* <input type="text" autoComplete="off" /> */}
            <Input
              placeholder="请输入手机号"
              value={mobile}
              name="mobile"
              onChange={handleChange}
              // autoComplete="off"//默认
              onBlur={handleBlur}
            ></Input>
            {touched.mobile && errors.mobile ? (
              <div className="validate">{errors.mobile}</div>
            ) : null}
          </div>
          <div className="input-item">
            <Input
              placeholder="请输入验证码"
              extra={time === 0 ? '获取验证码' : time + '秒后获取'}
              onExtraClick={onExtraClick}
              value={code}
              name="code"
              onChange={handleChange}
              onBlur={handleBlur}
            ></Input>
            {touched.code && errors.code ? (
              <div className="validate">{errors.code}</div>
            ) : null}
          </div>
          {/* 登录按钮 */}
          <button
            type="submit"
            className={classNames('login-btn', { disabled: !isValid })}
            disabled={!isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
